<template>

    <div>
        <!-- 面包屑导航 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/quesManage' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>问卷列表</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 搜索筛选 -->
        <el-form :inline="true" :model="formInline" ref="formInline" class="paper-search" style="margin-top: 20px" >
            <el-form-item label="搜索：" prop="paperInfo">
                <el-input  size="small" v-model="formInline.paperInfo" placeholder="输入关键字"/>
            </el-form-item>
            <el-form-item prop="status">
                <el-select  size="small" v-model="formInline.status" placeholder="选择问卷状态">
                    <el-option
                            v-for="item in options"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value">
                    </el-option>
                </el-select>
            </el-form-item>

            <el-form-item prop="startTime">
                    <el-date-picker
                            size="small"
                            v-model="formInline.startTime"
                            align="right"
                            type="date"
                            placeholder="选择开始日期"
                            :picker-options="pickerOptions">
                    </el-date-picker>
            </el-form-item>
            <el-form-item prop="endTime">
                    <el-date-picker
                            size="small"
                            v-model="formInline.endTime"
                            align="right"
                            type="date"
                            placeholder="选择结束日期"
                            :picker-options="pickerOptions"
                            @change="changeDate()">
                    </el-date-picker>
            </el-form-item>

            <el-form-item>
                <el-button size="small" @click="resetForm('formInline')">重置</el-button>
            </el-form-item>
            <el-form-item>
                <el-button size="small" type="primary" icon="el-icon-search" @click="search()">搜索</el-button>
            </el-form-item>
        </el-form>
        <el-button  size="small" type="primary" round @click="add()" icon="el-icon-circle-plus">新增问卷</el-button>
        <el-button  size="small" type="primary" round @click="recycle()" icon="el-icon-delete">回收站</el-button>
        <el-table
                v-loading="loading"
                ref="paperTable"
                :data="tableData.slice((currentPage-1)*pagesize,currentPage*pagesize)"
                tooltip-effect="dark"
                stripe
                :cell-style="cellStyle"
                :header-cell-style="headerCellStyle"
                @selection-change="handleSelectionChange">
            <el-table-column
                    type="selection"
                    width="30">
            </el-table-column>
            <el-table-column
                    prop="title"
                    label="问卷列表"
                    sortable
                    width="220">
                <template slot-scope="scope">{{scope.row.title}}</template>
            </el-table-column>
            <el-table-column
                    prop="totalCount"
                    label="参与人数"
                    sortable
                    width="100">
                <template slot-scope="scope">{{scope.row.totalCount}}</template>
            </el-table-column>
            <el-table-column
                    prop="createTime"
                    label="创建日期"
                    sortable
                    width="110">
                <template slot-scope="scope">{{scope.row.createTime}}</template>
            </el-table-column>
            <el-table-column
                    prop="startTime"
                    label="开始日期"
                    sortable
                    width="110"
                    show-overflow-tooltip>
                <template slot-scope="scope">{{scope.row.startTime}}</template>
            </el-table-column>
            <el-table-column
                    prop="endTime"
                    label="截止日期"
                    sortable
                    width="110"
                    show-overflow-tooltip>
                <template slot-scope="scope">{{scope.row.endTime}}</template>
            </el-table-column>
            <el-table-column
                    prop="status"
                    label="状态"
                    sortable
                    width="80"
                    show-overflow-tooltip
            >
                <template slot-scope="scope">
                    <el-tooltip :content="scope.row.status === '0' ? '发布状态: 禁用' : '发布状态: 发布中'" placement="top">
                        <el-switch
                                active-value = '1'
                                inactive-value = '0'
                                v-model="scope.row.status"
                                @change="quesStatus(scope.row)"/>
                    </el-tooltip>
                </template>

            </el-table-column>
            <el-table-column
                    prop="adminName"
                    label="创建人"
                    sortable
                    width="100"
                    show-overflow-tooltip>
                <template slot-scope="scope">{{scope.row.adminName}}</template>
            </el-table-column>
            <el-table-column
                    prop="handle"
                    label="操作"
                    show-overflow-tooltip>
                <template slot-scope="scope">
                    <!--查看问卷信息-->
                    <el-button
                            icon="el-icon-search"
                            circle
                            @click="queryPaper(scope.row)">
                    </el-button>
                    <!--修改问卷信息-->
                    <el-button type="primary"
                               icon="el-icon-edit"
                               circle
                               @click="updatePaper(scope.row)">
                    </el-button>
                    <!--删除问卷-->
                    <el-button type="danger"
                               icon="el-icon-delete"
                               circle
                               @click="deletePaper(scope.row.paperId)">
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
        <div style="margin-top: 20px;display: inline-block;width:100%;" :inline="true">
            <el-button size="small" type="danger" @click="stopSelection()">禁用选中项</el-button>
            <el-button size="small" type="success" @click="startSelection()">启用选中项</el-button>
            <el-button size="small" type="info" @click="toggleSelection()">取消选择</el-button>
            <!--分页-->
            <el-pagination
                    style="float: right;margin-right: 30px"
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="currentPage"
                    :page-sizes="[5, 10, 20]"
                    :page-size="pagesize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="tableData.length">
            </el-pagination>
        </div>

    </div>
</template>
<script>
    import {
        fuzzyQuery,
        getPaperDetail,
        paperLists,
        deletePaper,
        updatePaper,
        updatePaperStatus
    } from "../../../api/paperMG";

    export function formatDate(date,format){

    }

    export default {
        name: "recycle_bin",

        data() {
            return {
                loading: true,
                value1: true,
                tableData: [],
                multipleSelection: [],

                //单选框-问卷状态
                options: [{
                    value: '0',
                    label: '未发布问卷'
                }, {
                    value: '1',
                    label: '已发布问卷'
                },{
                    value: '2',
                    label: '往期问卷'
                }],
                //搜索问卷信息对象
                formInline: {
                    paperInfo: '',
                    status: '',
                    startTime: '',
                    endTime: ''
                },

                //选择日期
                pickerOptions: {
                    disabledDate(time) {
                        return time.getTime() > Date.now();
                    },
                    shortcuts: [{
                        text: '今天',
                        onClick(picker) {
                            picker.$emit('pick', new Date());
                        }
                    }, {
                        text: '昨天',
                        onClick(picker) {
                            const date = new Date();
                            date.setTime(date.getTime() - 3600 * 1000 * 24);
                            picker.$emit('pick', date);
                        }
                    }, {
                        text: '一周前',
                        onClick(picker) {
                            const date = new Date();
                            date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
                            picker.$emit('pick', date);
                        }
                    }]
                },
                //分页
                currentPage:1, //初始页
                pagesize:10,    //每页的数据

            }
        },
        methods: {

            //重置
            resetForm(formName) {
                this.$refs[formName].resetFields();
            },
            async quesStatus(paperInfo) {
                if (paperInfo.status === '1'){
                    this.$confirm('此操作将开启该问卷发布，发布后该问卷可被参与，是否继续?', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                        updatePaper(paperInfo).then(res=>{

                            if (res.code === 200) {
                                this.$message.success("问卷发布成功");
                            }
                            else{
                                this.$message.error(res.msg, {duration: 3 * 1000});
                                this.getQuesList();
                            }
                        });
                    }).catch(()=>{
                        paperInfo.status = '0';
                        this.$message.error('发布已取消！')
                    })
                }

                else {
                    this.$confirm('此操作将终止该问卷的发布，终止后该问卷将停止参与，是否继续?', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                        updatePaper(paperInfo).then(res=>{
                            if (res.code === 200) {
                                this.$message.warning("问卷终止成功");
                            }
                            else {
                                this.$message.error(res.msg, {duration: 3 * 1000});
                                this.getQuesList();
                            }
                        });
                    }).catch(()=>{
                        paperInfo.status = '1';
                        this.$message.error('发布终止已取消！')
                    })
                }

            },

            toggleSelection(rows) {
                console.log(rows);
                if (rows) {
                    rows.forEach(row => {
                        this.$refs.paperTable.toggleRowSelection(row);
                        console.log(rows)
                    });
                } else {
                    this.$refs.paperTable.clearSelection();
                }
            },

            handleSelectionChange(val) {
                this.multipleSelection = val;
            },

            stopSelection() {
                this.$confirm('此操作将终止所有选中问卷的发布，终止后所有选中问卷将被禁用，是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    const paperIds = [];
                    this.multipleSelection.forEach(row=>{
                        paperIds.push(row.paperId)
                    });
                    const paperInfo = {
                        paperIds : paperIds,
                        status : '0'
                    };
                    updatePaperStatus(paperInfo).then(res=>{
                        if (res.code === 200) {
                            this.getQuesList();
                            this.$message.warning('禁用成功！')
                        }
                        else {
                            this.$message.error(res.msg, {duration: 3 * 1000});
                        }
                    });
                })
            },

            //启用选中项
            startSelection() {
                this.$confirm('此操作将开启所有选中问卷发布，发布后问卷可被参与，是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    const paperIds = [];
                    this.multipleSelection.forEach(row=>{
                        paperIds.push(row.paperId)
                    });
                    const paperInfo = {
                        paperIds : paperIds,
                        status : '1'
                    };
                    updatePaperStatus(paperInfo).then(res=>{
                        if (res.code === 200) {
                            this.getQuesList();
                            this.$message.success('发布成功！')
                        }
                        else {
                            this.$message.error(res.msg, {duration: 3 * 1000});
                        }
                    });
                })
            },

            //初始化问卷列表
            async getQuesList() {
                paperLists().then(res => {
                    if (res.code === 200) {
                        console.log("===========初始化问卷列表===========");
                        this.tableData = res.data;
                        this.loading = false;
                        return ;
                    }
                    this.loading = false;
                    return this.$message('获取用户列表失败！')
                });
            },

            // 初始页currentPage、初始每页数据数pagesize和数据data
            handleSizeChange: function (size) {
                this.pagesize = size;
                console.log(this.pagesize)  //每页下拉显示数据
            },
            handleCurrentChange: function(currentPage){
                this.currentPage = currentPage;
                console.log(this.currentPage)  //点击第几页
            },

            //搜索
            search() {
                console.log("this.startTime",this.formInline.startTime);
                console.log("this.endTime",this.formInline.endTime);
                console.log("!this.paperInfo",(!this.paperInfo));
                console.log("this.paperInfo",this.formInline.paperInfo);
                console.log("this.status",this.formInline.status);
                console.log("!this.startTime",(!this.startTime));
                console.log("this.startTime == \"\"",this.startTime === "");

                const params = {
                    "remark": this.formInline.paperInfo,
                    "status": this.formInline.status,
                    "createTime": this.formInline.createTime,
                    "startTime": this.formInline.startTime,
                    "endTime": this.formInline.endTime,
                };
                console.log("this.params=====>",params);
                fuzzyQuery(params).then(res=>{
                    console.log("res.data",res.data);
                    this.tableData = res.data;
                    this.loading = false;
                    console.log("res.data=====>",res.data);
                })
            },

            //表格单元格样式设计 --wzr 20210418
            headerCellStyle() {
                return "text-align: center;";
            },

            cellStyle({row, column, rowIndex, columnIndex}) {//根据测试结果动态调整单元格样式，成功-绿色，失败-红色，不支持-黄色
                return "text-align: center;";
                let cellStyle;
                //指定列
                if (columnIndex === 5) {

                }
                switch (row.testResult) {
                    case '成功':
                        cellStyle = 'background: green;color:white';
                        break;
                    case '失败':
                        cellStyle = 'background: red;color:white';
                        break;
                    case '不支持':
                        cellStyle = 'background: #aaa;color:white';
                        break;
                    default:
                        cellStyle = '';
                }
                if (column.label === '测试结果')
                    return cellStyle;
            },

            //查询问卷内容
            queryPaper(paper) {
                getPaperDetail(paper).then(res=>{
                   console.log("问卷数据=====>",res);
                    this.$router.push({name:"QuesDetail",params:res.data})
                });
            },
            //修改问卷内容
            updatePaper(paper) {
                getPaperDetail(paper).then(res=>{
                    console.log("问卷数据=====>",res);
                    this.$router.push({name:"Update",params:res.data})
                });
            },

            //删除问卷
            deletePaper(paperId){
                this.$confirm('此操作将删除该问卷, 删除后可在回收站查询此问卷，是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    console.log("===============>",paperId);
                    const params = {
                        "paperIds":[paperId],
                        "flag":"1"
                    };console.log("===============>",params);
                    deletePaper(params).then(res=>{
                        console.log("res=====>",res);
                        console.log("res.code=====>",res.code);
                        if (res.code === 200){
                            this.$message({
                                type: 'success',
                                message: '删除成功!'
                            });
                            this.getQuesList();
                        }
                    });

                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            },

            //时间转换
            changeDate() {
                console.log(this.date);
                const transfer = date => `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()} 00:00:00`;
                console.log("transfer",transfer);
                let startTime = transfer(this.date[0]);
                let endTime = transfer(this.date[1]);
                const newPaperInfo = {
                    ...this.paperInfo,
                    startTime,
                    endTime
                };
                console.log(newPaperInfo);
            },

            //新增问卷
            add(){
                this.$router.push({name:"Create"})
            },

            //回收站
            recycle() {
                this.$router.push({name:"RecycleBin"})
            }
        },
        created() {
            this.getQuesList();
            let info={}
            fuzzyQuery(info).then(res=>{
                console.log("res===>",res)
            });// 缓存
        }
    }
</script>

<style scoped>
    .el-pagination {
        display: inline-block;
    }
</style>